package controllers

import (
	"net/http"
	"encoding/json"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"git.oschina.net/YPTArch/auth/models"
	"io/ioutil"
)

//用户登录
func Login(w http.ResponseWriter, r *http.Request) {
	logs.Logger.Debug("success in login")

	var result models.Result
	data, err := ioutil.ReadAll(r.Body)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"登录读取请求失败！", Data:""}
	}

	generateTokenResponse, err := loginHandler(data)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"登录处理失败！", Data:""}
	}else {
		result = models.Result{Code:models.Ok, Msg:"登录成功！", Data:generateTokenResponse}
	}

	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)
}

func loginHandler(data []byte) (generateTokenResponse models.GenerateTokenResponse, err error)   {

	//------解析部分-----
	var generateTokenRequest models.GenerateTokenRequest
	err = json.Unmarshal(data, &generateTokenRequest)
	if err != nil {
		logs.Logger.Error("login umarshall user err:"+err.Error())
		return
	}

	user := generateTokenRequest.User

	return saveTokenAndRefresh(&user, generateTokenRequest.IsGenRefresh)
}

